<script>
import { version } from 'vue'
import DirIcon from './assets/dir.png'
import FileIcon from './assets/file.png'
import { get, post } from './request.js'

function getErrorText(text = 'ERROR : 发生错误') {
  return `<div style='color:red;text-align: center;font-size: 18pt;'>${text}</div>`
}

export default {
  data() {
    return {
      DirIcon,
      FileIcon,
      // dirBaseId : -1 根目录 ， 0 版本目录 ， n 文件目录
      dirBaseId: -1,
      dirThisId: -1,
      dirFiles: [
        {
          fileName: 'Dir',
          dir: 1,
        },
        {
          fileName: 'App.vue',
          dir: 0,
        },
        {
          fileName: 'File',
          dir: 0,
        }
      ],
      dirParents: [],
      form: {
        version: '1.0',
        fileName: 'App.vue',
        filePath: 'http://117.72.40.39/files/te.html',
        type: null,//img / text / none = text
      },
      inLoading: false,
      fileText: '',
      fullText: '',
    }
  },
  created() {
    this.loadBaseDir()
  },
  mounted() {
    this.onResize()
    window.addEventListener("resize", this.onResize);
    this.getFile()
  },
  methods: {
    onResize(e) {
      let topH = (window.innerHeight - document.getElementById("OCTop").clientHeight - 8) + "px";
      document.getElementById("fileViewer").style.height = topH;
      document.getElementById("fileChoose").style.height = topH;
    },
    loadBaseDir() {
      this.dirBaseId = -1;
      this.dirThisId = -1;
      this.dirParents = [];
      this.dirFiles = [];
      this.form = {};
      get('/anon/oc/list').then(res => {
        console.log(res)
        this.dirFiles = res.result;
      })
    },
    async chooseFile(item) {
      if (item.dir == 1) {
        //文件夹选中
        await this.chooseDir(item);
      }
      else {
        //文件选中
        this.form = item;
        this.getFile();
      }
    },
    async chooseDir(item, id) {
      if (this.dirBaseId == -1) {
        await get('/anon/oc/listDirVersion', { dirName: item.fileName }).then(res => {
          console.log(version)
          this.dirFiles = res.result;
          this.dirBaseId = 0;
        });
      } else {
        await get('/anon/oc/listDir', { id: id | item.id }).then(res => {
          this.dirFiles = res.result;
          this.dirBaseId = item.id;
        })
      }
      this.getParents();
    },
    getFile() {
      this.inLoading = true;
      let filePath = 'http://oc.reyv.site/files/' + this.form.filePath;
      //图片
      const imgTypeArr = ['jpg', 'png', 'gif', 'jpeg', 'bmp', 'svg', 'webp'];
      for (let i = 0; i < imgTypeArr.length; i++) {
        if (filePath.endsWith(imgTypeArr[i])) {
          this.form.type = 'img';
          this.fileText = filePath;
          this.inLoading = false;
          return;
        }
      }
      //文字 / 其他格式
      let that = this;
      let xhr = new XMLHttpRequest();
      xhr.open('GET', filePath, true);
      xhr.responseType = 'blob';
      xhr.onload = function () {
        const reader = new FileReader()
        reader.onload = function () {
          that.fullText = reader.result;
          var tempArray = reader.result.split('\n');
          that.fileText = tempArray;
          that.form.type = 'text';
          // that.fileText = fileText;
          that.inLoading = false;
        }
        reader.readAsText(this.response);
      }
      xhr.send();
    },
    copyLine(index) {
      let result = this.fileText[index];
      navigator.clipboard.writeText(result).then(
        function () {
          let classArr = document.getElementsByClassName("copySuccess");
          if (classArr.length > 0) {
            let arr = Array.from(classArr);
            arr.forEach(item => {
              // item.classList.remove("copySuccess");
            })
          }
          document.getElementById(`viewerTypeRow${index}`).classList.add("copySuccess");
        },
        function () {
          alert('复制失败！无剪切板权限！');
        }
      );
    },
    copyFile() {
      let that = this;
      navigator.clipboard.writeText(that.fullText).then(
        function () {
          alert(`文件 ${that.form.fileName} - 版本 ${that.form.version} 复制成功！`);
        },
        function () {

        }
      )
    },
    OCLogoClick() {
      window.open('http://www.reyv.site');
    },
    getParents() {
      get('/anon/oc/getFileParents', { id: this.dirBaseId }).then(res => {
        this.dirParents = res.result.reverse();
      })
    }
  },
}
</script>

<template>
  <YvRow :span="40" id="OCTop" align="center">
    <YvCol :span="8" :sm="40" id="OCLogo" @click="OCLogoClick">
      <span class="OCStylePrimary">R</span>
      <span class="OCStyleContent">eYour</span>
      <span class="OCStylePrimary">O</span>
      <span class="OCStyleContent">penSource</span>
      <span class="OCStylePrimary">C</span>
      <span class="OCStyleContent">alendar</span>
    </YvCol>
    <YvRow :span="28" :sm="40" align="center">
      <YvCol :span="20" :sm="40">当前文件: {{ form.fileName }} - {{ form.version }}</YvCol>
      <YvCol :span="20" :sm="40">文件路径:
        <span v-if="!form.fileName">
          未选择
        </span>
        <a v-else :href='"http://oc.reyv.site/files/" + form.filePath' target="_blank">
          {{ dir == 1 ?
    form.filePath + '\-(.*)' :
    "http://oc.reyv.site/files/" + form.filePath
          }}
        </a>
      </YvCol>
    </YvRow>
    <YvRow :span="4">
      <YvBtn color="#000000" @click="copyFile">复制文件</YvBtn>
    </YvRow>
  </YvRow>
  <YvRow :span="40" id="OCContent">
    <YvCol :span="0" :sm="40">
      分辨率不支持！请更换PC查看或使用更改分辨率！
    </YvCol>
    <YvCol :span="8" :sm="0">
      <div id="fileChoose">
        <div id="fileChooseInfo">
          当前路径:
          <span>
            <a @click="loadBaseDir">根目录</a>{{ dirParents.length < 4 ? ' / ' : ' /../ ' }} </span>
              <span v-if="dirBaseId != -1">
                <span v-for="item in dirParents.slice(-3)">
                  <a @click="chooseDir(item)">{{ item.fileName }}</a> /
                </span>
              </span>
        </div>
        <div class="fileChooseItem" v-for="(item, index) in dirFiles" @click="chooseFile(item)">
          <img class="fileTypeIcon" v-if="dirBaseId != 0" :src="item.dir == 1 ? DirIcon : FileIcon" />
          <span class="fileItemText">{{ dirBaseId == 0 ? item.version : item.fileName }}</span>
        </div>
      </div>
    </YvCol>
    <YvCol :span="32" :sm="0">
      <YvRow id="fileViewer">
        <div id="noFileChoose" v-if="!form">
          未选择文件
        </div>
        <YvCol id="inLoading" v-else-if="inLoading">
          正在加载中...
        </YvCol>
        <div id="viewer" v-else>
          <div class="viewerType viewerTypeImg" v-if="form.type == 'img'">
            正常显示 : 图片
            <img :src="form.filePath" />
          </div>
          <div class="viewerType " v-else>
            <div v-for="(item, index) in fileText" class="textRow" @click="copyLine(index)">
              <div class="rowIndex" :id="'viewerTypeRow' + index">
                <span class="viewerTypeRow">
                  {{ index }}
                </span>
              </div>
              <div class="text">
                <span class="viewerTypeText">
                  {{ item }}
                </span>
              </div>
            </div>
          </div>
        </div>
      </YvRow>
    </YvCol>
  </YvRow>

</template>

<style scoped>
@font-face {
  font-family: 'yv-cn-sanjinhei';
  font-display: swap;
  src: url('./assets/font/cn/hei-sanjin.ttf');
}

@font-face {
  font-family: 'yv-en-idea';
  font-display: swap;
  src: url('./assets/font/english/idea-mono.ttf');
}

* {
  font-family: 'yv-en-idea', 'yv-cn-sanjinhei';
}

#OCLogo :hover {
  cursor: pointer;
}

#OCTop {
  min-height: 4vh;
  padding: 5pt 0pt;
  vertical-align: middle;
}

#inLoading {
  align-items: center;
  justify-content: center;
}

.OCStylePrimary {
  font-size: 20pt;
  font-weight: bold;
  color: rgba(245, 207, 15, 1);
  text-shadow: 0px 1px 2px rgba(252, 5, 5, 0.5);
}

#fileViewer {
  border-radius: 10pt;
  text-align: left;
  overflow: scroll;
  border: 1px solid black;
  width: 98%;
  background: rgb(250, 250, 250);
}

.copySuccess {
  position: relative;
  color: green;
}

.copySuccess::after {
  content: "√";
  position: absolute;
  left: 0;
  font-size: 6pt;
  padding: 0 4pt;
  /* border: 1px solid black; */
  border-radius: 2pt;
}

::-webkit-scrollbar {
  width: 2px;
  height: 4px;
  background: transparent;
}

::-webkit-scrollbar-thumb {
  height: 5px;
  background: #00C3FF;
}

#fileChoose {
  border-radius: 5pt;
  width: 98%;
  border: 1px solid black;
  background: rgb(250, 250, 250);
  /* padding: 5pt 0; */
  z-index: 1;
  overflow-y: auto;
  overflow-x: hidden;
}

.fileChooseItem {
  display: flex;
  width: 100%;
  text-align: left;
  height: 20pt;
  vertical-align: middle;
  padding: 4pt 0;
  border-bottom: 1px solid;
  border-image: linear-gradient(to right, white, gray, white) 1;
}

.fileChooseItem:hover {
  /* justify-content: center; */
  z-index: 0;

  animation-duration: 600ms;
  cursor: pointer;
  background: linear-gradient(to right, rgb(244, 244, 244), white);
  animation-name: identifier;
  color: #00C3FF;
}

#fileChooseInfo {
  font-size: 8pt;
}

.viewerType {
  word-break: pre;
  width: auto;
  display: block;
  white-space: pre;
  word-wrap: break-word;
}

.textRow:hover {
  color: #00C3FF;
  cursor: copy;
}

.textRow>div {
  display: inline-block;
  vertical-align: middle;
  line-height: 20pt;
}

.rowIndex {
  border-right: 1px solid black;
  text-align: center;
  width: 45pt;
  font-size: 12pt;
  border-bottom: 1px solid black;
  margin-right: 2pt;
}

@keyframes identifier {
  0% {
    color: #000000;

    background: transparent;

    margin-left: 0pt;
  }

  50% {
    background: transparent;
    color: #006686;

    margin-left: 20pt;
  }

  100% {
    background: transparent;

    color: #00C3FF;
    margin-left: 0pt;
  }
}

.fileTypeIcon {
  margin: 0pt 4pt;
  height: 18pt;
  width: 18pt;
  vertical-align: middle;

}

.fileItemText {
  font-size: 12pt;
  vertical-align: middle;
}
</style>
